/////////////////////////////////////////////////////////////////////////
//
// Amuse Engine SDK - core/threads
// Copyright (c) 2014.  All Rights Reserved
//
// File:		AESemaphore_posix.cpp
// Author:		Gianluca Belardelli
// Date:		01/06/2014
//
/////////////////////////////////////////////////////////////////////////
#include <AECore.h>

AESemaphore::AESemaphore( void )
{
}

AESemaphore::AESemaphore( AEINT32 nValue, AEINT32 nMax )
{
	AEASSERT( nValue >= 0 && nMax > 0 && nValue <= nMax );

	sem_init( &m_hSemaphore, 0, nValue );
}

AESemaphore::~AESemaphore( void )
{
	sem_close( &m_hSemaphore );
	sem_destroy( &m_hSemaphore );
}
	
AEINT32 AESemaphore::Set( void )
{
	sem_post( &m_hSemaphore );
	return AESemaphore_Ok;
}

AEINT32 AESemaphore::WaitInfinite( void )
{
	sem_wait( &m_hSemaphore );
	return AESemaphore_Ok;
}

AEINT32 AESemaphore::Wait( AEINT32 uiMilliseconds )
{
	struct timespec ts;

	ts.tv_sec = uiMilliseconds / 1000;
	ts.tv_nsec = (uiMilliseconds % 1000)*1000000;

	sem_timedwait( &m_hSemaphore, &ts );
	return AESemaphore_Ok;
}
